<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #app {
            display: flex;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="form-group">
            <label for="username">用户名:</label>
            <input type="text" class="username" name="username" id="username" placeholder="输入用户名" />
            <span>*</span>
        </div>
    </div>

</body>
<script>
    //获得焦点
    let username = document.querySelector('.username')
    username.addEventListener('focus', function (e) {
        let span = this.nextElementSibling//this就是username
        span.innerHTML = 'input获得焦点了'
    })

    //输入事件 input元素获取用户输入
    username.addEventListener('input', function (e) {
        let span = this.nextElementSibling//this就是username
        span.innerHTML = this.value

        validUsername()
    })

    //失去焦点时触发
    username.addEventListener('blur', function (e) {
        let span = this.nextElementSibling
        span.innerHTML = 'input失去焦点了'
    })

    //4、change事件常用在radio checkbox select file 内容发生变化是
    // username.addEventListener("change", function(e) {
    //   let span = this.nextElementSibling
    //   span.innerHTML = 'input变化了'
    // })

    //5、键盘事件 键盘按下时
    username.addEventListener("keydown", function (e) {
        // .keyCode是获取按下键盘按键的Unicode值 数字
        let keyCode = e.keyCode
        console.log(keyCode)
        if (keyCode === 13) {
            let span = this.nextElementSibling
            span.innerHTML = '回车'
        }
    })

    /**
     * 描述 验证输入的用户名是否符合要求 首位是字母，6-12，非空
     * @date 2020-09-29
     * @returns {boolean}
     */
    function validUsername() {
        let v = username.value
        let span = username.nextElementSibling
        span.innerHTML = ''
        span.style.color = 'red'
        //判断空 .trim()首尾去空格操作

        if (v.trim() === "") {
            span.innerHTML = '用户名不能为空'
            return false;
        }
        //判断首位字母
        let code = v[0]
        let str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        if (str.indexOf(code) === -1) {
            span.innerHTML = '用户名首位必须是字母'
            return false;
        }
        //判断长度
        if (v.length > 12 || v.length < 6) {
            span.innerHTML = '用户名长度6-12位'
            return false;
        }
        span.innerHTML = '用户名正确'
        span.style.color = 'green'
        return true;
    }
</script>

</html>